//
//  KKOAuthLoginController.swift
//  KKWeibo
//
//  Created by kassia on 16/7/10.
//  Copyright © 2016年 kassia. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


//  微博appKey
let weiboAppKey = "3381690248"
//  微博appsecret
let weiboAppSecret = "0829b8589d244f16b61c4a6226213e14"
//  微博授权回调页
let weiboRedirect_Uri = "http://www.taobao.com"

class KKOAuthLoginController: UIViewController {

    
    //懒加载 webView
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        
        //自定义视图
        webView.delegate = self
        
        //默认不透明,,改为false                    
        webView.opaque = false
        
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()

        requestOAuthLogin()
    }

    //界面基本设置
    private func setUpUI() {
        
        navigationItem.title = "微博登录"
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, title: "取消", action: "cancleAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(target: self, title: "自动填充", action: "autoFillAction")
    
    }
    
    
    private func requestOAuthLogin() {
    
        //请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAppKey)&redirect_uri=\(weiboRedirect_Uri)"
        
        //请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        //加载请求
        webView.loadRequest(request)
    
    }

    // MARK: -- 点击事件
    
    @objc private func cancleAction() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func autoFillAction() {
        
        print("点击了自动填充按钮")
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18872252627'; document.getElementById('passwd').value = 'sakura4010'")
        
    }

}

//webView的代理
extension KKOAuthLoginController: UIWebViewDelegate {

    
    //https://www.taobao.com/?code=fb2050f6b76f64c7de70d44ee1f28bcc
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            
        return false
        
        }
        
        //  代码执行到此,我们的url一定有值
        //  获取url的绝对地址
        if !url.absoluteString.hasPrefix(weiboRedirect_Uri) {
        
        return true
            
        }
        
        if let query = url.query where query.hasPrefix("code=") {
        
            //截取code
            let code = query.substringFromIndex("code=".endIndex)
            
            KKUserAccountModel.sharedUserAccount.requestAccessToken(code, callback: { (isSucess) -> () in
                
                if isSucess {
                
                    print("登录成功")
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
                        //发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName("SwitchRootVCNotification", object: self)
                        
                        
                    })
                
                } else {
                
                    print("登录失败")
                
                }
                
            })
            
        } else {
            
            //取消回调页
           dismissViewControllerAnimated(true, completion: nil)
        
        }
        
        return false
    }

    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}
